"""React相关的衍生配置处理"""

from typing import Dict, Any
from src.base import bera

def derive_react_config(meta_info: Dict[str, Any]) -> Dict[str, Any]:
    """处理meta.json的React相关衍生配置

    处理字段级衍生配置:
    - columns.*.derived.react.type: React/TypeScript类型
    - columns.*.derived.react.form_component: 表单组件类型
    - columns.*.derived.react.display_component: 显示组件类型
    - columns.*.derived.react.validation_rule: 验证规则
    - columns.*.derived.react.default_value: React默认值

    :param meta_info: meta.json格式的结构体
    :return: 更新后的结构体,可以继续传递给其他derived函数处理
    """
    bera.logger.debug("====== 开始处理React相关衍生配置 ======")

    # 遍历处理每个column
    for column_name, column_info in meta_info["columns"].items():
        try:
            # 基于TypeScript类型
            ts_type = column_info.get("derived", {}).get("ts", {}).get("type", "string")

            # Vue组件到React组件的映射
            vue_component = column_info.get("derived", {}).get("ui", {}).get("vue_antd_component", "a-input")

            vue_to_react_component_map = {
                "a-input": "Input",
                "a-input-number": "InputNumber",
                "a-textarea": "Input.TextArea",
                "a-select": "Select",
                "a-date-picker": "DatePicker",
                "a-switch": "Switch",
                "a-checkbox": "Checkbox",
                "a-radio": "Radio"
            }

            react_form_component = vue_to_react_component_map.get(vue_component, "Input")

            # 显示组件（一般都是文本显示）
            react_display_component = "span"
            if ts_type == "boolean":
                react_display_component = "Tag"
            elif vue_component in ["a-date-picker"]:
                react_display_component = "span" # 日期格式化显示

            # 验证规则
            validation_rules = []
            if column_info.get("common", {}).get("required", False):
                validation_rules.append("{ required: true, message: '请输入" + column_info.get("common", {}).get("label", column_name) + "' }")

            # 根据类型添加特定验证
            if ts_type == "number":
                validation_rules.append("{ type: 'number', message: '请输入有效数字' }")
            elif vue_component == "a-input" and column_info.get("sql", {}).get("type", {}).get("length"):
                max_length = column_info["sql"]["type"]["length"]
                validation_rules.append(f"{{ max: {max_length}, message: '长度不能超过{max_length}个字符' }}")

            validation_rule = "[" + ", ".join(validation_rules) + "]" if validation_rules else "[]"

            # 默认值
            react_default_value = {
                "string": "''",
                "number": "0",
                "boolean": "false"
            }.get(ts_type, "''")

            # 添加derived配置
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "react" not in column_info["derived"]:
                column_info["derived"]["react"] = {}

            column_info["derived"]["react"]["type"] = ts_type
            column_info["derived"]["react"]["form_component"] = react_form_component
            column_info["derived"]["react"]["display_component"] = react_display_component
            column_info["derived"]["react"]["validation_rule"] = validation_rule
            column_info["derived"]["react"]["default_value"] = react_default_value

        except Exception as e:
            bera.logger.warning(f"处理列 {column_name} 的React配置时出错: {str(e)}")
            # 如果转换失败,使用默认配置
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "react" not in column_info["derived"]:
                column_info["derived"]["react"] = {}

            column_info["derived"]["react"]["type"] = "string"
            column_info["derived"]["react"]["form_component"] = "Input"
            column_info["derived"]["react"]["display_component"] = "span"
            column_info["derived"]["react"]["validation_rule"] = "[]"
            column_info["derived"]["react"]["default_value"] = "''"

    bera.logger.debug("====== React相关衍生配置处理完成 ======")
    return meta_info